package com.leetcode.no15;

import java.lang.reflect.Array;
import java.util.*;

public class Solution {
    List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> threeSum(int[] nums) {
        if (nums.length < 1) {
            return res;
        }

        Arrays.sort(nums);

        for (int left = 0; left < nums.length - 2; left++) {
            if (nums[left] > 0) {
                break;
            }

            if (left > 0 && nums[left] == nums[left - 1]) {
                continue;
            }

            int right = nums.length - 1;
            int mid = left + 1;

            while (mid < right) {
                int sum = nums[left] + nums[mid] + nums[right];
                if (sum < 0) {
                    while (mid < right && nums[mid] == nums[++mid]) ;
                } else if (sum > 0) {
                    while (mid < right && nums[right] == nums[--right]) ;
                } else {
                    res.add(new ArrayList<Integer>(Arrays.asList(nums[left], nums[mid], nums[right])));

                    while (mid < right && nums[left] == nums[++mid]) ;
                    while (mid < right && nums[right] == nums[--right]) ;

                }
            }

        }

        return res;
    }


}
